﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class 防止SQL注入 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

            CheckStr();

    }
    public  void CheckStr()//防止SQL注入
    {
        string url, ip,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8;
        //ToUpper把字母變成大寫的
        url = Request.QueryString.ToString();//得到?后面的字符串
        ip = Request.ServerVariables["REMOTE_ADDR"].ToString();//取远程用户IP地址 
        pos1 = url.IndexOf("%").ToString();//查找字串中指定字符或字串首次（最后一次）出现的位置,返回索引值
        pos2 = url.IndexOf("'").ToString();
        pos3 = url.IndexOf(";").ToString();
        pos4 = url.IndexOf("where").ToString();
        pos5 = url.IndexOf("select").ToString();
        pos6 = url.IndexOf("chr").ToString();
        pos7 = url.IndexOf("/").ToString();
        pos8 = url.IndexOf("and").ToString();


        //SQL注入东东看看有没有 这个是URL的
        if ((int.Parse(pos1) != -1) || (int.Parse(pos2) != -1) || (int.Parse(pos3) != -1) || (int.Parse(pos4) != -1) || (int.Parse(pos5) != -1) || (int.Parse(pos6) != -1) || (int.Parse(pos7) != -1) || (int.Parse(pos8) != -1))
        {
            Response.Write(pos1);
            Response.Write("你在搞什么");
        }
        Response.Write(url.ToUpper());
        //以下开始表单里的数据;
        string 表单;
            int j,i;
            j=Request.Form.Count;//得到表单的总数

            for ( i = 0; i < j; i++)
            {
                表单 = Request.Form[i].ToString();
                if ((表单.IndexOf("'") != -1) || (表单.IndexOf(";") != -1))
                {
                    Response.Write("<script language='javascript'>history.back(); alert('你尝试使用危险字符,系统已经对此做了记录如下您的IP:" + ip + "操作时间:" +DateTime.Today.ToString().Substring(0,10) + "');</script>");
                    Response.End();
                }
            }
        //Form的东东
    }
}
